package com.p2p.front.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.p2p.base.exception.BizException;
import com.p2p.base.model.BaseUser;
import com.p2p.base.model.Money;
import com.p2p.base.page.PageVo;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.BankCard;
import com.p2p.front.dal.model.MemberPoint;
import com.p2p.front.dal.model.MemberPointLog;
import com.p2p.front.dal.model.UserCredits;
import com.p2p.front.dal.model.Withdraw;
import com.p2p.front.enums.UserCreditsType;
import com.p2p.front.service.BankCardService;
import com.p2p.front.service.ChargeService;
import com.p2p.front.service.CommonService;
import com.p2p.front.service.MemberPointService;
import com.p2p.front.service.UserCreditsService;
import com.p2p.front.service.WithdrawService;
import com.p2p.front.web.form.WithdrawForm;
import com.p2p.trans.client.facade.AccountQueryFacade;
import com.p2p.trans.client.result.AccountQueryResult;
import com.p2p.user.facade.UserQueryFacade;
import com.p2p.user.result.UserQueryResult;

/**
 * leiwen@yiqihao.com
 */
@Controller
@RequestMapping(value = "/withdraw")
public class WithdrawController extends BaseController {

	@Resource
	private WithdrawService withdrawService;

	@Resource
	private MemberPointService memberPointService;

	@Resource
	private AccountQueryFacade accountQueryFacade;

	@Resource
	private BankCardService bankCardService;

	@Resource
	private UserQueryFacade userQueryFacade;

	@Resource
	private CommonService commonService;
	
	@Resource
	private UserCreditsService userCreditsService;
	
	@Resource
	private ChargeService chargeService;
	
	@RequestMapping("/index.html")
	public String index(ModelMap map) {
		BaseUser user = getCurrentUser();
		AccountQueryResult result = accountQueryFacade.getAccountInfo(user.getAccountNo());

		if (!result.isSuccess()) {
			map.addAttribute("err", result.getResultCode());
			return "errorPage";
		}
		map.addAttribute("userInfo", result.getAccountVO());
		List<BankCard> cardList = bankCardService.listAllCardByUser(user
				.getId());
		map.put("cardList", cardList);

		MemberPoint memberPoint = memberPointService.getUserMemberPoint(user
				.getId());
		map.put("memberPoint", memberPoint);
		
		UserCredits userCreditsNeedCharge = userCreditsService.getByUserAndTypeAutoCreate(user.getId(), UserCreditsType.UserCreditsNeedCharge);
		Money amount = new Money(userCreditsNeedCharge.getValue());
		map.put("needChargeAmount", amount.getYuan());
		return "/withdraw/index";
	}

	@RequestMapping(value = "/list")
	public String list(PageVo form, Model model) {
		BaseUser user = getCurrentUser();
		form.getParams().put("uid", user.getId());
		form.handleIntDate();
		PageVo page = withdrawService.listPage(form);
		form.resetDate();
		model.addAttribute("page", page);
		return "withdraw/list";
	}

	// TODO 后面在加前端AJAX异步验证
	@RequestMapping("checkPaypwd")
	public void checkPaypwd(String paypwd, Model model) {
		BaseUser user = getCurrentUser();
		UserQueryResult result = userQueryFacade.getUserInfoById(user.getId());
		String realPaypwd = result.getUserInfoFullVO().getPaypwd();
		boolean allBlank = StringUtils.isBlank(paypwd)
				&& StringUtils.isBlank(realPaypwd);

		if (allBlank || paypwd.equals(realPaypwd)) {
			model.addAttribute("", "");
		} else {

		}
	}

	@RequestMapping("applyWithdrawCash")
	public String applyWithdrawCash(HttpServletRequest request,
			WithdrawForm withdrawForm, ModelMap map) {
		// card不能为空
		if (StringUtils.isBlank(withdrawForm.getCard())) {
			throw new BizException("withdraw_error", "银行卡号提现金额不能为空");
		}

		if (withdrawForm.getMoney() == null || withdrawForm.getMoney() <= 0) {
			throw new BizException("withdraw_error", "提现金额不能为空，必须大于0");
		}
		BaseUser user = getCurrentUser();
		AccountQueryResult result = accountQueryFacade.getAccountByUserId(user
				.getId());

		if (!result.isSuccess()) {
			map.addAttribute("err", result.getResultCode());
			throw new BizException("account_error", "查询账户信息失败");
		}

		// 提现额度不能超过可用余额
		Long canUseMoney = result.getAccountVO().getCanUserBalance().getCent();
		Long withdrawMoney = (long) (withdrawForm.getMoney() * 100);
		if (withdrawMoney > canUseMoney) {
			throw new BizException("withdraw_error", "提现金额不能超过可用余额");
		}

		boolean paypwdRight=commonService.checkPaypwd(withdrawForm.getPaypwd(), user.getLongId());
		if(!paypwdRight){
			throw new BizException("PAYPWD_ERROR", "支付密码不正确");
		}
		// 校验通过
		BankCard bankCard = bankCardService.getBankCard(user.getId(),
				withdrawForm.getCard());

		boolean pointResult = false;
		Integer score = withdrawForm.getUsescore();
		if (score != null) {
			pointResult = memberPointService.cumulative(user.getId(), 200,
					MemberPointLog.TypeEnum.WITHDRAW_FEE);
			if (!pointResult) {
				map.addAttribute("err", "积分不足");
				throw new BizException("point_error", "积分不足");
			}
		}

		Withdraw withdraw = new Withdraw();
		if (pointResult) {
			withdraw.setScore(200);
			withdraw.setFee(new Money(0L));
		} else {
			withdraw.setFee(new Money(2, 0));
		}
		
		Money money = doubleToMoney(withdrawForm.getMoney());
		UserCredits userCredits = userCreditsService.getByUserAndTypeAutoCreate(user.getId(), UserCreditsType.UserCreditsNeedCharge);
		Money feeDrawMoney = calcuFeedrawMoney(canUseMoney,userCredits.getValue(),withdrawMoney);
		withdraw.setFeeDraw(feeDrawMoney);
		
		withdraw.setArea(bankCard.getArea());
		withdraw.setCity(bankCard.getCity());
		withdraw.setUid(Integer.parseInt(user.getId()));
		withdraw.setCode(bankCard.getCode());
		withdraw.setCard(withdrawForm.getCard());
		withdraw.setBranch(bankCard.getBranch());
		withdraw.setBank(bankCard.getBank());
		withdraw.setName(bankCard.getName());
		withdraw.setAddtime(System.currentTimeMillis());
		withdraw.setUptime(System.currentTimeMillis());
		// withdraw.setFee(doubleToMoney(withdrawForm.getFee()));
		withdraw.setMoney(money);
		withdraw.setAddip(getRemoteIp(request));
		withdraw.setUpip(getRemoteIp(request));
		
		
		withdrawService.save(withdraw, result.getAccountVO());
		return "/withdraw/notify";
	}

	// 将Double格式的10.01元转换成Money格式的1000分
	private Money doubleToMoney(Double d) {
		if (d == null) {
			d = 0.00;
		}
		Double cent = d * 100;
		Long l = (long) cent.intValue();
		return new Money(l);
	}

	private Money calcuFeedrawMoney(long canUseMoney,long UserCreditsNeedChargeMoney,long withdrawMoney){
		//免费金额
		long freeCent = canUseMoney-UserCreditsNeedChargeMoney;
		//收费金额
		long feeDrawCent = withdrawMoney-freeCent;
		if(feeDrawCent<0l){
			feeDrawCent=0l;
		}
		return new Money(feeDrawCent);
	}
}
